﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
using System.Web.Mvc;
using Lvzhi.AdminCenter.Models;
using Lvzhi.Core;
using Lvzhi.Entities;
using Lvzhi.Entities.BaseEnum;
using Lvzhi.Provide.Auth;
using Lvzhi.Provide.EncryptHelper;
using Lvzhi.Provide.JsonHelper;
using Lvzhi.Provide.Rpg;
using Newtonsoft.Json;

namespace Lvzhi.AdminCenter.Controllers
{
    public class PassportController : Controller
    {
        private UserCore aCore = new UserCore();
        //
        // GET: /Passport/

        public ActionResult Login()
        {
            //ViewBag.LoginTips = Md5Extensions.MD5Decrypt("781950FD700677A8");
            return View();
        }
        [HttpPost]
        public ActionResult Login(FormCollection obj)
        {
            string name = obj["uname"];
            string pwd = obj["pwd"];
            string rememberMe = obj["rememberMe"];
            var admin = aCore.LoadEntity(o => o.U_Name.Equals(name));
            if (admin != null && admin.U_Pwd.Equals(Md5Extensions.MD5Encrypt(pwd + admin.U_EncryptCode)))  //通过登录验证
            {
                admin.U_Lasttime = DateTime.Now;
                admin.U_LoginCount += 1;

                aCore.UpdateEntity(admin);


                Sys_OperateLog log = new Sys_OperateLog()
                {
                    L_Desc = "",
                    L_DriverType = 0,
                    L_Flag = (int)LogTypeEnum.登陆,
                    L_Phone = admin.U_Phone,
                    L_Status = 0,
                    L_Time = DateTime.Now,
                    L_UId = admin.U_Id.ToString(),
                };
                new OperateLogCore().AddEntity(log);




                FormTicketHelper.SetCookie(admin.U_Name, string.Format("{0},{1}", admin.U_Role, admin.U_Id), "on".Equals(rememberMe));
                string rurl = Request.QueryString["ReturnUrl"];
                if (!string.IsNullOrEmpty(rurl))
                {
                    return Redirect(rurl);
                }
                return RedirectToAction("Index", "Console");
                ViewBag.LoginTips = "登录成功咯哦" + rememberMe + "on".Equals(rememberMe) + FormTicketHelper.IsLogin();
            }
            else
            {
                ViewBag.LoginTips = "帐号密码不匹配";
            }
            return View();
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            FormTicketHelper.Logout();
            CookieHelper.ClearCookie("manager");
            return RedirectToAction("Login");
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpFile()
        {
            var obj = FileUpload();
            return Json(obj, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        public ResultDataModel FileUpload()
        {
            var obj = new ResultDataModel();

            var file = ControllerContext.HttpContext.Request.Files["userfile"];
            string folder = ControllerContext.HttpContext.Request["Folder"].ToString();
            string optionType = ControllerContext.HttpContext.Request["Type"].ToString();  //文件类型，(后面可根据文件类型限制上传文件的大小）
            string strFileName = ControllerContext.HttpContext.Request["FileName"]; //自定义的上传文件名
            string useOldFileName = ControllerContext.HttpContext.Request["UseOldFileName"];  //使用上传的文件名


            string waterMark = ControllerContext.HttpContext.Request["WaterMark"]; //是否加水印

            if (file == null)
            {
                obj.Msg = "文件不存在";
                return obj;
            }

            string oldName = file.FileName;  //原文件名
            strFileName = Guid.NewGuid().ToString("N") + oldName;  //重命名文件名


            int bytes = ControllerContext.HttpContext.Request.Files[0].ContentLength;
            string contentType = ControllerContext.HttpContext.Request.Files[0].ContentType;
            string strLocation = string.Empty;
            //缩放图的路径 （统一上传到指定的物理盘符目录）
            string filePhyPath = ControllerContext.HttpContext.Server.MapPath("~/cache/");// System.Configuration.ConfigurationManager.AppSettings["StaticFilePath"]; // 
            string path = filePhyPath + folder + "/";  //构造文件上传的物理目录
            ControllerContext.HttpContext.Response.ContentType = "text/plain";

            int maxLen = 0;
            switch (optionType)
            {
                case "Image":
                    maxLen = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ImgSize"].ToString());

                    break;
                case "Video":
                    maxLen = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VideoSize"].ToString());
                    break;
                case "Excel":
                    maxLen = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ExcelSize"].ToString());
                    break;
            }
            //如果，上传的文件过大的话，抛消息出来
            if (bytes > maxLen)
            {
                obj.Msg = "文件太大";
                return obj;
            }

            if (!Directory.Exists(path))  //如果上传文件夹不存在，创建
            {
                Directory.CreateDirectory(path);
            }
            strLocation = path + strFileName;  //上传文件的完整路径

            ControllerContext.HttpContext.Request.Files[0].SaveAs(strLocation);

            //资源文件存放的RUL
            string url = "/cache/"; //System.Configuration.ConfigurationManager.AppSettings["ImgSiteUrl"];//

            string msg = string.Format("{0}|{1}|{2}|{3}|{4}", strFileName, folder, url + folder + "/" + strFileName, oldName, bytes);
            obj.Code = 0;
            obj.Msg = msg;
            return obj;
        }

        public JsonResult UpExcel()
        {
            var obj = FileUpload();

            if (obj.Code > -1)
            {
                string filepath = Server.MapPath(obj.Msg.Split('|')[2]); //excel 路径
                string oleDBConnString = String.Empty;
                oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
                oleDBConnString += "Data Source=";
                oleDBConnString += filepath;
                oleDBConnString += ";Extended Properties=Excel 8.0;";
                OleDbConnection oleDBConn = null;
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();

                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {

                    m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString();

                }
                string sqlMaster;
                sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();

//                var tb = ds.Tables[0];
//                if (tb.Rows.Count>1)
//                {
//                    foreach (var item in tb.Rows)
//                    {
//                        
//                    }
//                }
//                else
//                {
//                    obj.Msg = "没有数据";
//                }

//              var list= TableToList<dynamic>(ds.Tables[0]);
                var list = ds.Tables[0];
                JsonSerializerSettings setting = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };

                var ret = JsonConvert.SerializeObject(list, setting);
                obj.Data = ret;

            }
            return Json(obj, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// DataTable转化为List集合
        /// </summary>
        /// <typeparam name="T">实体对象</typeparam>
        /// <param name="dt">datatable表</param>
        /// <param name="isStoreDB">是否存入数据库datetime字段，date字段没事，取出不用判断</param>
        /// <returns>返回list集合</returns>
        public   List<T> TableToList<T>(DataTable dt, bool isStoreDB = true)
        {
            List<T> list = new List<T>();
            Type type = typeof(T);
            List<string> listColums = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                PropertyInfo[] pArray = type.GetProperties(); //集合属性数组
                T entity = Activator.CreateInstance<T>(); //新建对象实例
                foreach (PropertyInfo p in pArray)
                {
                    if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
                    {
                        continue;  //DataTable列中不存在集合属性或者字段内容为空则，跳出循环，进行下个循环
                    }
                    if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01"))
                    {
                        continue;
                    }
                    try
                    {
                        var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//类型强转，将table字段类型转为集合字段类型
                        p.SetValue(entity, obj, null);
                    }
                    catch (Exception)
                    {
                        // throw;
                    }
                    //if (row[p.Name].GetType() == p.PropertyType)
                    //{
                    //    p.SetValue(entity, row[p.Name], null); //如果不考虑类型异常，foreach下面只要这一句就行
                    //}
                    //object obj = null;
                    //if (ConvertType(row[p.Name], p.PropertyType,isStoreDB, out obj))
                    //{                    
                    //    p.SetValue(entity, obj, null);
                    //}
                }
                list.Add(entity);
            }
            return list;
        }

        public ActionResult Test()
        {
            var m = new
            {
                name="abc",
                age  = 1,
                email = "11@qq.com"
            };
            string mmp = JsonSerialize.Instance.ObjectToJson(m);

            string email = JsonSerialize.Instance.JsonToObject(mmp).email;
            return Content(mmp+"----"+email);
        }
    }
}
